﻿using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HobSoft.SoccerBet2014.Domain.Common.Site
{
    using Component;
    using Models.Site;

    public partial class SboSessionManager : SessionManagerBase
    {
        protected virtual string CreateSignFormContent(string account, string password, string token)
        {
            StringBuilder sbContent = new StringBuilder();
            sbContent.AppendFormat("id={0}", account);
            sbContent.AppendFormat("&password={0}", password);
            sbContent.AppendFormat("&lang={0}", "zh-CN");
            string odToken = string.Empty;
            if (OdTokenValues != null && OdTokenKeys != null)
            {
                odToken = string.Join(",", OdTokenValues.ToArray());
            }
            sbContent.AppendFormat("&tk={0}", odToken);
            sbContent.AppendFormat("&type={0}", "form");
            string dtVal = string.Empty;
            if (SiteTokenKeys != null && SiteTokenValues != null)
            {
                var dtIndex = SiteTokenKeys.IndexOf("dt");
                if (dtIndex > -1)
                    dtVal = SiteTokenValues[dtIndex];
            }
            sbContent.AppendFormat("&timestamp={0}", dtVal);
            return sbContent.ToString();
        }

        protected override bool CheckLoginHtmlState(string html)
        {
            if (html.Contains("你的密碼已過期"))
            {
                LoginState = LoginState.NeedChangePassword;
                return false;
            }
            if (html.IndexOf("/zh-cn/page/force-change-password", StringComparison.OrdinalIgnoreCase) > -1)
            {
                LoginState = LoginState.NeedChangePassword;
                return false;
            }
            if (html.Contains("/page/error?type=sign-in"))
            {
                LoginState = LoginState.UserNameOrPasswordError;
                return false;
            }
            if (html.IndexOf("logout.aspx", 0, StringComparison.OrdinalIgnoreCase) != -1 || html.IndexOf("<title>Logout</title>", 0, StringComparison.OrdinalIgnoreCase) != -1)
            {
                LoginState = LoginState.BeenSignedOut;
                _loginInfo.IsLogin = false;
                return false;
            }
            if (html.Contains("name='error' value='6'") || html.Contains("name='error' value='3'"))
            {
                LoginState = LoginState.UserNameOrPasswordError;
                return false;
            }
            if (html.Contains("name='error' value='5'"))
            {
                LoginState = LoginState.CodeError;
                return false;
            }
            if (html.Contains("設置您的偏好設定"))
            {
                LoginState = LoginState.NeedSetting;
                return false;
            }
            return true;
        }

        protected override bool ValidHostIsWWW(string host)
        {
            string wwwHost = string.Format("www.{0}", GlobalHost);
            return host.Equals(wwwHost, StringComparison.OrdinalIgnoreCase);
        }

        protected override string WWWHost()
        {
            return string.Format("www.{0}", GlobalHost);
        }

        public async override Task<bool> Signout()
        {
            CookiesManager.Clear(BookerID, Account);
            return true;
        }

        public async override Task StartHeartbeat()
        {

        }

        public async override Task<bool> CheckSession()
        {
            string url = string.Format(@"http://{0}/web-root/restricted/default.aspx?loginname={1}&redirect=true", Host, SessionLoginName.Value);
            var reqTask = GetHtmlRequest(new Uri(url), url, false);
            var result = await reqTask;
            if (reqTask.IsCanceled || reqTask.Exception != null) return false;
            if (string.IsNullOrEmpty(result))
            {
                _loginInfo.IsLogin = false;
                _loginInfo.LastRequestTime = DateTime.Now;
                LoginState = LoginState.BeenSignedOut;
                return false;
            }
            if (!CheckLoginHtmlState(result))
                return false;
            return true;
        }

        protected override void SetMainRequestTick()
        {
            Random rand = new Random();
            MainRequestTick = rand.Next(90, 300);
        }
    }
}
